//
//  CircleHomeViewController.m
//  nonghubao
//
//  Created by Fenrir on 13-10-21.
//  Copyright (c) 2013年 Chongqing Nonghubao Co., Ltd. All rights reserved.
//

#import "CircleHomeViewController.h"
#import "CircleListViewController.h"
#import "JSONRequest.h"
#import "JMFBase.h"
#import "MembersViewController.h"
#import "CircleFormViewController.h"
#import "CirclePickerInProcessViewController.h"
#import "CustomUISearchDisplayController.h"
#import "ASImageView.h"
#import "pinyin.h"
#import "CirclePickerViewController.h"
#import "PersonalViewController.h"

@interface CircleHomeViewController ()<UITableViewDataSource, UITableViewDelegate, JSONRequestDelegate, CirclePickerDelegate, UISearchBarDelegate, UISearchDisplayDelegate>

@end

@implementation CircleHomeViewController
{
    UIButton *_circlesButton;           //圈子列表切换按钮
    UIButton *_friendsButton;           //好友列表切换按钮
    BOOL _viewLoaded;
    UITableView *_tableView;
    
    BOOL *_tab;                         //用于区别当前tableview处于什么类型，YES为圈子列表，NO为好友列表
    
    UISearchBar *_searchBar;
    CustomUISearchDisplayController* __searchDisplayController;   //搜索结果控制器
    
    NSArray *_circlesArray;                     //圈子数据源
    NSArray *_friendsArray;                     //好友列表数据源
    NSMutableArray *_sectionForFriendsArray;    //按首字母分组后的好友列表数据源
    NSMutableArray *_filterFriendsArray;        //通过用户搜索过滤后的好友列表数据源
    
    NSInteger _modifyingFriendId;               //当前正在被选择圈子的好友的id
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
        _tab = NO;
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	
    if (iOS7) {
        self.edgesForExtendedLayout = UIRectEdgeLeft | UIRectEdgeBottom | UIRectEdgeRight;
    }
    self.title = _L(@"vc_title_099");
    
    //设置空白处背景颜色
    self.view.backgroundColor = _SYS_COLOR_BACKGROUND;
    
    //左侧按钮：返回
    UIButton* backButton = [Helper buttonWithStyle:ButtonStyleNavigationReturn];
    backButton.tag = 100;
    [backButton addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    //右侧按钮：添加
    UIButton* addButton = [Helper buttonWithStyle:ButtonStyleNavigationAdd];
    addButton.tag = 101;
    [addButton addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:addButton];
    
    _friendsButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, _SYS_FRAME_WIDTH / 2, 40)];
    _friendsButton.titleLabel.font = _SYS_FONT_004;
    _friendsButton.tag = 103;
    [_friendsButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_friendsButton setTitle:_L(@"btn_title_04") forState:UIControlStateNormal];
    [_friendsButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_bg_001@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_friendsButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_bg_002@2x" ofType:@"png"]] forState:UIControlStateHighlighted];
    [_friendsButton addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_friendsButton];
    
    _circlesButton = [[UIButton alloc] initWithFrame:CGRectMake(_SYS_FRAME_WIDTH / 2, 0, _SYS_FRAME_WIDTH / 2, 40)];
    _circlesButton.titleLabel.font = _SYS_FONT_004;
    _circlesButton.tag = 102;
    _circlesButton.highlighted = YES;
    [_circlesButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_circlesButton setTitle:_L(@"btn_title_03") forState:UIControlStateNormal];
    [_circlesButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_bg_001@2x" ofType:@"png"]] forState:UIControlStateNormal];
    [_circlesButton setBackgroundImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"transaction_bg_002@2x" ofType:@"png"]] forState:UIControlStateHighlighted];
    [_circlesButton addTarget:self action:@selector(buttonEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_circlesButton];
    
    [self tableViewToShow];
    [self obtainFriendsDataWithPage:0];
    [self search];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (_tab) {
        JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_LIST];
        request.delegate = (id)self;
        
        //第一次装载视图要显示菊花，根据_viewLoaded的值来判断
        if (_viewLoaded == false) {
            [request setHUD:HUDStyleModeTitle withView:self.view];
            request.hudTitle = _L(@"title_loading_01");
            
            //更新_viewLoaded标记的值，使下次界面载入时不再显示菊花
            _viewLoaded = true;
        }
        
        [request asynchronous];
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 事件

- (void)buttonEvent:(id)sender
{
    UIButton *clickedButton = (UIButton *)sender;
    
    if (clickedButton.tag == 100) {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    //添加
    else if (clickedButton.tag == 101) {
        //圈子列表时，应为添加圈子，否则为添加好友
        if (_tab) {
            CircleFormViewController* circleFormVC = [[CircleFormViewController alloc] init];
            
            UINavigationController* circleFormNC = [[UINavigationController alloc] initWithRootViewController:circleFormVC];
            
            [Helper navigationControllerCommonStyle:circleFormNC];
            
            [self.navigationController presentModalViewController:circleFormNC animated:true];
        }
        else {
            CirclePickerInProcessViewController* circlePickerVC = [[CirclePickerInProcessViewController alloc] initWithStyle:UITableViewStyleGrouped];
            
            circlePickerVC.delegate = self;
            
            UINavigationController* circleNavigationController = [[UINavigationController alloc] initWithRootViewController:circlePickerVC];
            
            [Helper navigationControllerCommonStyle:circleNavigationController];
            
            [self.navigationController presentModalViewController:circleNavigationController animated:true];
            
        }
    }
    else if (clickedButton.tag == 102) {
        _circlesButton.highlighted = NO;
        _friendsButton.highlighted = YES;
        
        _tab = YES;
        _tableView.tableHeaderView = nil;
        
        [self tableViewToShow];
        [self obtainCirclesData];
    }
    else if (clickedButton.tag == 103) {
        _circlesButton.highlighted = YES;
        _friendsButton.highlighted = NO;
        
        _tab = NO;
        [self tableViewToShow];
        [self obtainFriendsDataWithPage:0];
        [self search];
    }
    else {
        
    }
}

//- (void)avatarTapped:(id)sender
//{
//    UITapGestureRecognizer *tapGestureRecognizer = (UITapGestureRecognizer *)sender;
//    
//    NSDictionary *friend;
//    NSIndexPath *indexPath;
//    
//    //获取对应tableview上的点击位置
//    if (tapGestureRecognizer.view.tag == 102) {
//        CGPoint currentTouchPosition = [tapGestureRecognizer locationInView:_tableView];
//        
//        indexPath = [_tableView indexPathForRowAtPoint:currentTouchPosition];
//        
//        friend = [[_sectionForFriendsArray objectAtIndex:indexPath.section-1] objectAtIndex:indexPath.row];
//    }
//    else if (tapGestureRecognizer.view.tag == 103) {
//        
//        CGPoint currentTouchPosition = [tapGestureRecognizer locationInView:__searchDisplayController.searchResultsTableView];
//        
//        indexPath = [__searchDisplayController.searchResultsTableView indexPathForRowAtPoint:currentTouchPosition];
//        friend = [_filterFriendsArray objectAtIndex:indexPath.row];
//    }
//    
//    if (indexPath != nil) {
//
//        PersonalInfoViewController *personalInfoVC = [[PersonalInfoViewController alloc] initWithPersonId:[friend[@"friendUserId"] integerValue]];
//        [self.navigationController pushViewController:personalInfoVC animated:YES];
//    }
//}

//点击自定义的accessoryButton时，让tableview相应accessoryButton的代理方法
- (void)modifyBtnClicked:(id)sender event:(id)event
{
    NSSet *touches =[event allTouches];
    UITouch *touch =[touches anyObject];
    
    if ([(UIButton *)sender tag] == 100) {
        CGPoint currentTouchPosition = [touch locationInView:_tableView];
        NSIndexPath *indexPath= [_tableView indexPathForRowAtPoint:currentTouchPosition];
        if (indexPath!= nil)
        {
            [self tableView: _tableView accessoryButtonTappedForRowWithIndexPath:indexPath];
        }
    }
    else if ([(UIButton *)sender tag] == 101) {
        CGPoint currentTouchPosition = [touch locationInView:__searchDisplayController.searchResultsTableView];
        NSIndexPath *indexPath= [__searchDisplayController.searchResultsTableView indexPathForRowAtPoint:currentTouchPosition];
        if (indexPath!= nil)
        {
            [self tableView: __searchDisplayController.searchResultsTableView accessoryButtonTappedForRowWithIndexPath:indexPath];
        }
    }
    else {
        
    }
    
    
}

/*!
 @abstract 圈子图片点击事件。
 通过获取sender的tag，可以得知被点击的圈子的ID
 */
- (void)imageButtonEvent:(id)sender
{
    CircleFormViewController* circleFormViewController = [[CircleFormViewController alloc] init];
    
    //通过sender.tag，从_dataSource中取到对应的Circle对象
    circleFormViewController.circle = [_circlesArray objectAtIndex:((UIButton *)sender).tag];
    
    [self.navigationController pushViewController:circleFormViewController animated:true];
}

#pragma mark - UITableView Datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    if (_tab) {
        return 1;
    }
    else {
        if (tableView == _tableView) {
            
            return _sectionForFriendsArray.count+1;
        }
        else {
            return 1;
        }
    }
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    if (_tab) {
        return _circlesArray.count;
    }
    else {
        
        if (tableView == _tableView) {
            if (section == 0) {
                return 2;
            }
            else {
                
                return [_sectionForFriendsArray[section-1] count];
            }
        }
        else {
            return _filterFriendsArray.count;
        }
        
    }
    
    
}

// 分区标题头(分区栏最上面出现对应abc...)
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (_tableView == tableView) {
        // 存在本地联系人数据
        if (_friendsArray.count > 0) {
            if (section == 0) {
                return nil;
            }
            // 如果当前分区对应数组中没有数据
            if ([[_sectionForFriendsArray objectAtIndex:section-1] count] > 0) {
                // 返回26个英文字母+1个＃号特殊字符中,指定分区索引的一个字母
                // 截取字符串解析  (26个英文字母+1个＃号特殊字符,指定分区索引开始截取 ＝ 保留右边数据) (右边数据只截取到索引1处 ＝ 保留左边数据)
                NSString *headerTitleString = [NSString stringWithFormat:@"%@", [[ALPHA substringFromIndex:section-1] substringToIndex:1]];
                
                return headerTitleString;
            }
            else {
                return nil;
            }
        }
    }

    return nil;
}

// 右侧A-Z
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    //正常表
    if (_tableView == tableView && !_tab) {
        // 存在本地地址薄数据
        if (_sectionForFriendsArray.count > 0) {
            NSMutableArray *indices = [NSMutableArray array];
            // 26个英文字母+1个＃号特殊字符
            for (int i = 0; i < 27; i++) {
                // 将首字母加入数组
                // 截取字符串解析  (26个英文字母中,指定分区索引开始截取 ＝ 保留右边数据) (右边数据只截取到索引1处 ＝ 保留左边数据)
//                if ([_sectionForFriendsArray[i] count] > 0) {
                
                    [indices addObject:[[ALPHA substringFromIndex:i] substringToIndex:1]];
//                }
            }
            return indices;
        }
    }
    
    // 查询表
	return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier_1 = @"Cell_Circles";
    static NSString *CellIdentifier_2 = @"Cell_Static_Label";
    static NSString *CellIdentifier_3 = @"Cell_Friends";
    
    if (_tab) {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier_1];
    
        if (cell == nil) {
        
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier_1];

            //圈子的图片，加入点击事件
            UIButton* imageButton = [[UIButton alloc] initWithFrame:CGRectMake(8, 5, 32, 32)];
            [imageButton setBackgroundImage:[UIImage imageNamed:@"dynamic_btn_001"] forState:UIControlStateNormal];
            [imageButton addTarget:self action:@selector(imageButtonEvent:) forControlEvents:UIControlEventTouchUpInside];
            
            [cell.contentView addSubview:imageButton];
            
            //圈子名字文字
            UILabel* contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 5, 170, 35)];
            contentLabel.font = _SYS_FONT_003;
            contentLabel.textColor = _SYS_COLOR_002;
            contentLabel.lineBreakMode = UILineBreakModeWordWrap;
            contentLabel.numberOfLines = 0;
            contentLabel.textColor = [UIColor blackColor];
            contentLabel.backgroundColor = [UIColor clearColor];
            [cell.contentView addSubview:contentLabel];
            
            //圈子统计文字
            UILabel* numberLabel = [[UILabel alloc] initWithFrame:CGRectMake(220, 5, 55, 35)];
            numberLabel.font = _SYS_FONT_004;
            numberLabel.textColor = [UIColor orangeColor];
            numberLabel.backgroundColor = [UIColor clearColor];
            numberLabel.textAlignment = UITextAlignmentRight;
            [cell.contentView addSubview:numberLabel];
        }
        
        NSDictionary* circle = _circlesArray[indexPath.row];
        UIButton* imageButton = cell.contentView.subviews[0];
        UILabel* contentLabel = cell.contentView.subviews[1];
        UILabel* numberLabel = cell.contentView.subviews[2];
        
        //设置本行的row值给图片，图片点击的时候就可以通过_dataSource的row行获取到Circle对象
        [imageButton setTag:indexPath.row];
        [contentLabel setText:circle[@"name"]];
        [numberLabel setText:[NSString stringWithFormat:@"（ %i ）", [circle[@"memberCount"] intValue]]];
        [numberLabel sizeToFit];
        numberLabel.frame = CGRectMake(cell.bounds.origin.x+cell.bounds.size.width-numberLabel.frame.size.width-50.0f, 5, numberLabel.frame.size.width, 35);
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        return cell;
    }
    else {
        
        if (indexPath.section == 0 && _tableView == tableView) {
            
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier_2];
            
            if (cell == nil) {
            
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier_2];
                
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(8, 5, 32, 32)];
                imageView.tag = 110;
                [cell.contentView addSubview:imageView];
                
                //圈子名字文字
                UILabel* contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 5, 170, 35)];
                contentLabel.font = _SYS_FONT_003;
                contentLabel.textColor = _SYS_COLOR_002;
                contentLabel.tag = 111;
                contentLabel.lineBreakMode = UILineBreakModeWordWrap;
                contentLabel.numberOfLines = 0;
                contentLabel.textColor = [UIColor blackColor];
                contentLabel.backgroundColor = [UIColor clearColor];
                [cell.contentView addSubview:contentLabel];
                
                if (indexPath.row == 0) {
                    imageView.image = [UIImage imageNamed:@"com_icon_018"];
                    contentLabel.text = _L(@"title_92");
                }
                else if (indexPath.row == 1) {
                    imageView.image = [UIImage imageNamed:@"com_icon_019"];
                    contentLabel.text = _L(@"title_93");
                }
                
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                
            }
            return cell;
        }
        else {
            
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier_3];
            
            if (cell == nil) {
            
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier_3];
                
                ASImageView* imageView = [[ASImageView alloc] initWithFrame:CGRectMake(8, 5, 35, 35)];
                imageView.image = [UIImage imageNamed:@"dynamic_btn_001"];
                [cell.contentView addSubview:imageView];
                
                UILabel* contentLabel = [[UILabel alloc] initWithFrame:CGRectMake(45, 5, 170, 35)];
                contentLabel.font = _SYS_FONT_003;
                contentLabel.textColor = _SYS_COLOR_002;
                contentLabel.lineBreakMode = UILineBreakModeWordWrap;
                contentLabel.numberOfLines = 0;
                contentLabel.textColor = [UIColor blackColor];
                contentLabel.backgroundColor = [UIColor clearColor];
                [cell.contentView addSubview:contentLabel];
                
                UIButton *modifyButton = [[UIButton alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 45.0f, 23.7f)];
                [modifyButton setBackgroundImage:[UIImage imageNamed:@"transaction_btn_002_n"] forState:UIControlStateNormal];
                [modifyButton setTitle:_L(@"btn_title_06") forState:UIControlStateNormal];
                [modifyButton addTarget:self action:@selector(modifyBtnClicked:event:) forControlEvents:UIControlEventTouchUpInside];
                modifyButton.titleLabel.font = _SYS_FONT_001;
                
                cell.accessoryView = modifyButton;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            NSDictionary* friend;
            
            if (tableView == _tableView) {
                friend = [[_sectionForFriendsArray objectAtIndex:indexPath.section-1] objectAtIndex:indexPath.row];
                cell.accessoryView.tag = 100; //TAG为100表示是当前tableview，为101表示searchcontroller的tableview
            }
            else {
                friend = [_filterFriendsArray objectAtIndex:indexPath.row];
                cell.accessoryView.tag = 101;
            }
            
            ASImageView *imageView = (ASImageView *)[cell.contentView.subviews objectAtIndex:0];
            
            [imageView setImageURL:[NSURL URLWithString:[friend objectForKey:@"previewAvatar"]] andSourceImageURL:nil forStyle:PictureStyleAvartPreview];
            
            [((UILabel *)[cell.contentView.subviews objectAtIndex:1]) setText:[friend objectForKey:@"friendRealName"]];
            
            return cell;
        }
    }
}

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if (_tab) {
        
        MembersViewController *membersVC = [MembersViewController new];
        membersVC.circle = _circlesArray[indexPath.row];
        [self.navigationController pushViewController:membersVC animated:YES];
    }
    else {
        if (tableView == _tableView) {
            if (indexPath.section == 0) {
                MembersViewController *membersVC = [MembersViewController new];
                //邀请中的好友被点击
                if (indexPath.row == 0) {
                    
                    membersVC.membersType = MembersInvitingType;
                    
                }
                //屏蔽中的好友被点击
                else if (indexPath.row == 1) {
                    membersVC.membersType = MembersBanType;
                }
                else {
                    
                }
                [self.navigationController pushViewController:membersVC animated:YES];
            }
            else {
                
                //点击好友列表的行
                NSDictionary *friend = [[_sectionForFriendsArray objectAtIndex:indexPath.section-1] objectAtIndex:indexPath.row];
                PersonalInfoViewController *personalInfoVC = [[PersonalInfoViewController alloc] initWithPersonId:[friend[@"friendUserId"] integerValue]];
                [self.navigationController pushViewController:personalInfoVC animated:YES];
            }
        }
        
        else {
            NSDictionary *friend = [_filterFriendsArray objectAtIndex:indexPath.row];
            PersonalInfoViewController *personalInfoVC = [[PersonalInfoViewController alloc] initWithPersonId:[friend[@"friendUserId"] integerValue]];
            [self.navigationController pushViewController:personalInfoVC animated:YES];
        }
    }
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _tableView) {
        _modifyingFriendId = [_sectionForFriendsArray[indexPath.section-1][indexPath.row][@"friendUserId"] integerValue];
    }
    else {
        _modifyingFriendId = [_filterFriendsArray[indexPath.row][@"friendUserId"] integerValue];
    }
    
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_MEMBER_RELATIONS];
    request.delegate = self;
    request.hudOn = YES;
    request.hudTitle = _L(@"title_loading_01");
    if (_modifyingFriendId != 0) {
        [request setValue:[NSNumber numberWithInteger:_modifyingFriendId] forParameter:@"peopleId"];
    }
    
    [request setSuccessSelector:@selector(relationInfoDidRecived:)];
    [request asynchronous];
}

#pragma mark - 私有方法

//获取圈子列表的信息
- (void)obtainCirclesData
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_LIST];
    request.delegate = self;
    request.hudOn = YES;
    request.hudTitle = _L(@"title_loading_01");
    [request asynchronous];
}

//获取好友列表数据
- (void)obtainFriendsDataWithPage:(NSInteger)pageIndex
{
    JSONRequest* request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_FRIEND_RELATIONS_LIST];
    request.delegate = self;
    request.hudOn = YES;
    request.hudTitle = _L(@"title_loading_01");
    
    if (pageIndex != 0) {
        [request setValue:@(pageIndex) forParameter:@"page"];
    }
    [request setSuccessSelector:@selector(friendsDataDidReceived:)];
    [request asynchronous];
}

//实例化一个tableview
- (void)tableViewToShow
{
    if (_tableView == nil) {

        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, 40.0f, 320.0f, _SYS_FRAME_HEIGHT-84.0f) style:UITableViewStylePlain];

        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
        
    }
}

//实例化一个searchBar和searchDisplayController
- (void)search
{
    // 查询工具条
    // 实例化查询条
    if (_searchBar == nil) {
        
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 46.0f)];
        _searchBar.keyboardType = UIKeyboardTypeTwitter;
        _searchBar.placeholder = _L(@"holder_47");   //请输入姓名首字母
        _searchBar.delegate = self;
        _searchBar.showsScopeBar = YES;
        _searchBar.keyboardType = UIKeyboardTypeASCIICapable;
    }
    
    _tableView.tableHeaderView = _searchBar;
    
    if (__searchDisplayController == nil) {
        
        //实例化搜索用的UISearchDisplayController
        __searchDisplayController = [[CustomUISearchDisplayController alloc] initWithSearchBar:_searchBar contentsController:self];
        __searchDisplayController.searchResultsDataSource = self;
        __searchDisplayController.searchResultsDelegate = self;
        __searchDisplayController.searchBar.barStyle = nil;
        __searchDisplayController.delegate = self;
        for (UIView *subview in __searchDisplayController.searchBar.subviews)
        {
            if ([subview isKindOfClass:NSClassFromString(@"UISearchBarBackground")])
            {
                [subview removeFromSuperview];
                break;
            }
        }
        __searchDisplayController.searchBar.backgroundColor = RGBCOLOR(227, 227, 227);
    }
}

//对好友列表数据源进行按首字母分组
- (NSMutableArray *)sectionForFriends
{
    NSMutableArray* sections = [[NSMutableArray alloc] init];
    
    // 组装分区表初始默认数组
    // 循环将27个数组加入 分区数组(27个数组代表26个英文字母+1个＃号特殊字符)
    for (int i = 0; i < 27; i++) {
        [sections addObject:[NSMutableArray array]];
    }
    
    // 循环姓名数组
    for (NSMutableDictionary* person in _friendsArray) {
        // 得到当前元素姓名
        NSString *contactsName = [person objectForKey:@"friendRealName"];
        
        // 1、得到姓名0索引位置的字符
        // 2、调用pinyin类实例方法pinyinFirstLetter并传入字符，判断传入的字符是汉字还是英文，如果是汉字返回汉字所属的字母，不属于汉字返回传入字符
        // 3、将拼音方法传回的字符组装成字符串
        // 4、并转换成大写格式
        NSString *sectionPinYinLetter = nil;
        NSUInteger firstLetterLocation = NSNotFound;
        //长度检查，空名字不截取
        if (contactsName != nil && contactsName.length > 0) {
            sectionPinYinLetter = [[NSString stringWithFormat:@"%c",pinyinFirstLetter([contactsName characterAtIndex:0])] uppercaseString];
            firstLetterLocation = [ALPHA rangeOfString:[sectionPinYinLetter substringToIndex:1]].location;
        }
        
        // 1、截取sectionUgoName的第一个字符
        // 2、并判断此字符在26个英文字母+#号的位置，并赋值
        
        // 如果在26个之中的字母组成数组中有这个位置
        if (firstLetterLocation != NSNotFound) {
            // 找到ugo分区数组，在这个索引位置对应的数组，并加入同样属于索引i对应元素，及UgoContacts类的对象
            [[sections objectAtIndex:firstLetterLocation] addObject:person];
        }
        // 否则不在26个英文字母之中，用ALPHA数组最后一个特殊#号位置数组统一加入管理
        else {
            [[sections objectAtIndex:[ALPHA length] - 1] addObject:person];
        }
    }
    
    return sections;
}

/*!
 @abstract 初始化分区数据(组装分区数组、姓名数组、根据abc...z  26个字母对应26个分区+1个特殊分区＃号，对应字母分区放入对应姓名字母开头实体)
 */
- (void) sectionInitData
{
    // 查看通讯簿是否存在数据
    if ([_friendsArray count] > 0) {
        // 清除以前分区数据
        _sectionForFriendsArray = nil;
        
        // 获取新分区数据
        _sectionForFriendsArray = [self sectionForFriends];
    }
}

#pragma mark - JSONRequestDelegate

//
- (void)requestDidLoadJSON:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if (_circlesArray != nil && _circlesArray.count != 0) {
            _circlesArray = nil;
        }
        
        _circlesArray = (NSArray *)jmf.data;
        [_tableView reloadData];
    }
    
    else {
        
        [Helper easyShowJMFStatus:jmf];
    }
}

//好友信息请求成功
- (void)friendsDataDidReceived:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        if (_friendsArray != nil && _friendsArray.count != 0) {
            _friendsArray = nil;
        }
        _friendsArray = (NSArray *)(jmf.data[@"friendsRelations"]);
        [self sectionInitData];
        
        [_tableView reloadData];
    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

//
- (void)relationInfoDidRecived:(NSDictionary *)dict
{
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:dict];
    
    if (jmf.status == JMStatusSucceed) {
        
        //过滤出好友和“我”的关系，即好友在我的哪些圈子里面
        NSMutableArray *relationArray = [NSMutableArray new];
        for (NSDictionary *circle in (NSArray *)jmf.data) {
            if ([circle[@"isExist"] integerValue]) {
                [relationArray addObject:circle];
            }
        }
        
        CirclePickerViewController* circlePickerVC = [[CirclePickerViewController alloc] initWithStyle:UITableViewStyleGrouped];
        circlePickerVC.delegate = self;
        circlePickerVC.pickedCircles = relationArray;
        UINavigationController* circleNavigationController = [[UINavigationController alloc] initWithRootViewController:circlePickerVC];
        
        [Helper navigationControllerCommonStyle:circleNavigationController];
        
        [self.navigationController presentModalViewController:circleNavigationController animated:true];

    }
    else {
        [Helper easyShowJMFStatus:jmf];
    }
}

- (void)requestFailWithNetworkUnavailabe
{
    [Helper showAlertWithTitle:@"" andMessage:_L(@"title_networkunavailabe")];
}


#pragma mark - UISearchDisplayDelegate delegate


- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
    [UIView animateWithDuration:0.5f animations:^{
        _friendsButton.alpha = 0.0f;
        _circlesButton.alpha = 0.0f;
        _tableView.frame = CGRectMake(0.0f, 0.0f, 320.0f, _SYS_FRAME_HEIGHT-84.0f);
    } completion:^(BOOL finished) {
        
        
    }];
}

- (void)searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
    [UIView animateWithDuration:0.5f animations:^{
        _friendsButton.alpha = 1.0f;
        _circlesButton.alpha = 1.0f;
        _tableView.frame = CGRectMake(0.0f, 40.0f, 320.0f, _SYS_FRAME_HEIGHT-84.0f);
    }];
}

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    if (_filterFriendsArray != nil && _filterFriendsArray.count != 0) {
        [_filterFriendsArray removeAllObjects];
    }
    
    // 获取符合条件的数组
    _filterFriendsArray = [Helper filterFriendsArray:_friendsArray withString:searchString];
    
    return YES;
}

- (void)dealloc
{
    _circlesArray = nil;
    _friendsArray = nil;
    _sectionForFriendsArray = nil;
    _filterFriendsArray = nil;
}

#pragma mark - CirclePickerViewController Delegate
- (void)circlesPicked:(NSArray *)circles
{
    NSString *mobiles = @"";
    if (circles && circles.count != 0) {
        //将多个圈子ID用逗号隔开
        
        for (int i = 0; i < circles.count; i++) {
            
            //如果是最后一个则不添加“，”
            if (i == circles.count - 1) {
                mobiles = [mobiles stringByAppendingFormat:@"%@", [[circles objectAtIndex:i] objectForKey:@"id"]];
            }else{
                mobiles = [mobiles stringByAppendingFormat:@"%@,", [[circles objectAtIndex:i] objectForKey:@"id"]];
            }
        }
    }
    
    // 接收用户修改后或未修改的圈子
    // 如果最初的圈子数组为空，那么直接请求，如果不为空，那么判断内容是否一样，不一样则删除以前的再请求添加，
    // 一样则不管
    //circles为用户已选择的圈子数组，_cicleDataSource为服务器所返回的圈子数组，用户更新后_cicleDataSource也要跟着更新；
    
    JSONRequest *request = [[JSONRequest alloc] initWithURLString:_JSON_URL_CIRCLE_MEMBER_CHANGE_RELATION];
    
    [request setValue:mobiles forParameter:@"circleIds"];
    [request setValue:[NSString stringWithFormat:@"%d", _modifyingFriendId] forParameter:@"targetUserId"];
    NSDictionary* responseData = [request synchronous];
    
    JMFBase* jmf = [[JMFBase alloc] initWithJSONDictionary:responseData];
    if (jmf.status != JMStatusSucceed) {
        [Helper easyShowJMFStatus:jmf];
    }
}
@end
